/**
 * Created by xc on 2017/11/21.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var DevBaseModel = require('./DevBaseModel');
var async  = require( 'async'); // 同步控制

//--------------------------------------------------------------------------------------
// Schema 结构
var DevDevIdfaModel = function(obj){
    DevBaseModel.call(this,obj);

    // 以下为表定义数据，需要的字段就填入
    // `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    // `app_id` varchar(100) NOT NULL DEFAULT '' COMMENT 'appstore 应用唯一标识',
    // `idfa` varchar(100) NOT NULL DEFAULT '' COMMENT '用户设备广告标识',
    // `create_time` datetime NOT NULL COMMENT '创建时间',
    // `update_time` datetime NOT NULL COMMENT '更新时间',
    // `update_by` varchar(50) DEFAULT NULL COMMENT '更新者',
    // `del_flg` int(11) NOT NULL DEFAULT '0' COMMENT '逻辑删除标识',

};

DevDevIdfaModel.prototype = new DevBaseModel();

// 取得表名
DevDevIdfaModel.prototype.getTableName = function(){
    return 'dev_idfa';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
DevDevIdfaModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'id='+this.id;
};


DevDevIdfaModel.prototype.saveAppIdAndIdfaToDB = function (appId, idfa, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('DevDevIdfaModel.js [saveAppIdAndIdfaToDB] getConErr' + getConErr);
            return callback(getConErr, null);
        }

        var sql =  ' INSERT INTO dev.dev_idfa (app_id, idfa, create_time, update_time) ' +
                   ' SELECT "'+ appId +'", "'+idfa+'", sysdate(),  sysdate() ' +
                   ' FROM dual ' +
                   ' WHERE NOT EXISTS ' +
                   '     ( SELECT id ' +
                   '      FROM dev.dev_idfa ' +
                   '      WHERE app_id = "' + appId + '" ' +
                   '        AND idfa = "'+ idfa +'" ) LIMIT 1; ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('DevDevIdfaModel.js [saveAppIdAndIdfaToDB] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })


};

//--------------------------------------------------------------------------------------
// 导出
module.exports = DevDevIdfaModel;